import React, { FC, Suspense } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Skeleton, Avatar, Row, Col, List, Statistic } from 'antd';
import { useModel, useRequest, Link } from 'umi';
import { Gauge, WordCloud, Liquid } from '@ant-design/charts';
import styles from './style.less';
import TopSearch from './TopSearch';
import type { ActivitiesType } from './data.d';
import { fakeChartData, queryActivities, queryTags } from './service';
import moment from 'moment';
import EditableLinkGroup from './EditableLinkGroup';

const links = [
  {
    title: '操作一',
    href: '',
  },
  {
    title: '操作二',
    href: '',
  },
  {
    title: '操作三',
    href: '',
  },
  {
    title: '操作四',
    href: '',
  },
  {
    title: '操作五',
    href: '',
  },
  {
    title: '操作六',
    href: '',
  },
];

const PageHeaderContent: FC<{ currentUser: Partial<API.User> }> = ({ currentUser }) => {
  const loading = currentUser && Object.keys(currentUser).length;
  if (!loading) {
    return <Skeleton avatar paragraph={{ rows: 1 }} active />;
  }
  return (
    <div className={styles.pageHeaderContent}>
      <div className={styles.avatar}>
        <Avatar size="large" src={currentUser.photo} />
      </div>
      <div className={styles.content}>
        <div className={styles.contentTitle}>
          早安，
          {currentUser.name}
          ，祝你开心每一天！
        </div>
        <div>欢迎进入聘用信息后台管理系统！（本页数据均为Mock）</div>
      </div>
    </div>
  );
};

const ExtraContent: FC<Record<string, any>> = () => (
  <div className={styles.extraContent}>
    <div className={styles.statItem}>
      <Statistic title="待处理任务" value={16} />
    </div>
    <div className={styles.statItem}>
      <Statistic title="工作时长" value={2223} suffix="min"/>
    </div>
  </div>
);

const Welcome: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  const { loading, data } = useRequest(fakeChartData);
  const { loading: activitiesLoading, data: activities = [] } = useRequest(queryActivities);
  const { loading: tagLoading, data: tagData } = useRequest(queryTags);

  const wordCloudData: any[] = (tagData?.list || []).map((item) => {
    return {
      id: +Date.now(),
      word: item.name,
      weight: item.value,
    };
  });

  const renderActivities = (item: ActivitiesType) => {
    const events = item.template.split(/@\{([^{}]*)\}/gi).map((key) => {
      if (item[key]) {
        return (
          <a href={item[key].link} key={item[key].name}>
            {item[key].name}
          </a>
        );
      }
      return key;
    });

    return (
      <List.Item key={item.id}>
        <List.Item.Meta
          avatar={<Avatar src={item.user.avatar} />}
          title={
            <span>
              <a className={styles.username}>{item.user.name}</a>
              &nbsp;
              <span className={styles.event}>{events}</span>
            </span>
          }
          description={
            <span className={styles.datetime} title={item.updatedAt}>
              {moment(item.updatedAt).fromNow()}
            </span>
          }
        />
      </List.Item>
    );
  };

  return (
    <PageContainer
      content={<PageHeaderContent currentUser={currentUser} />}
      extraContent={<ExtraContent />}
    >
      <Row gutter={24}>
        <Col xl={16} lg={24} md={24} sm={24} xs={24}>
          <Card
            bodyStyle={{ padding: 0 }}
            bordered={false}
            className={styles.activeCard}
            title="动态"
            loading={activitiesLoading}
          >
            <List<ActivitiesType>
              loading={activitiesLoading}
              renderItem={(item) => renderActivities(item)}
              dataSource={activities}
              className={styles.activitiesList}
              size="large"
            />
          </Card>

          <div style={{ marginTop: 24 }}>
            <Suspense fallback={null}>
              <TopSearch
                loading={loading}
                visitData2={data?.visitData2 || []}
                searchData={data?.searchData || []}
                dropdownGroup={null}
              />
            </Suspense>
          </div>
        </Col>

        <Col xl={8} lg={24} md={24} sm={24} xs={24}>
          <Card
            style={{ marginBottom: 24 }}
            title="快速开始 / 便捷导航"
            bordered={false}
            bodyStyle={{ padding: 0 }}
          >
            <EditableLinkGroup onAdd={() => {}} links={links} linkElement={Link} />
          </Card>
          <Card
            title="审核效率"
            style={{ marginBottom: 24 }}
            bodyStyle={{ textAlign: 'center' }}
            bordered={false}
          >
            <Gauge
              height={180}
              autoFit
              percent={0.8}
              range={{
                ticks: [0, 1],
                color: ['l(0) 0:#F4664A 0.5:#FAAD14 1:#30BF78'],
              }}
              indicator={{
                pointer: {
                  style: {
                    stroke: '#D0D0D0',
                  },
                },
                pin: {
                  style: {
                    stroke: '#D0D0D0',
                  },
                },
              }}
              statistic={{
                content: {
                  content: '优',
                  style: {
                    color: '#30bf78',
                  },
                },
              }}
            />
          </Card>
          <Card
            title="岗位剩余"
            bodyStyle={{ textAlign: 'center', fontSize: 0, marginBottom: 24 }}
            bordered={false}
          >
            <Liquid
              height={161}
              percent={0.25}
              outline={{
                border: 4,
                distance: 8,
              }}
              wave={{
                length: 128,
              }}
            />
          </Card>
          <Card
            title="热门搜索"
            loading={tagLoading}
            bordered={false}
            bodyStyle={{ overflow: 'hidden' }}
          >
            <WordCloud
              data={wordCloudData}
              height={162}
              wordStyle={{
                fontSize: [10, 20],
              }}
              wordField="word"
              weightField="weight"
            />
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default Welcome;
